package com.autoscript.endpoint;

import com.autoscript.utils.ContextUtils;
import com.autoscript.utils.SessionMap;
import com.autoscript.utils.WebSocketList;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;


//
@ServerEndpoint("/websocket/{loginSession}/{logNumber}")
@Component
@Data
//此注解相当于设置访问URL
public class WebSocket {
    private static final Logger log = LoggerFactory.getLogger("websocket");
    private Session session;
    private String loginSession;
    private String logNumber;
    private Date createTime;
    @Autowired
    private WebSocketList webSocektList;
    @Autowired
    private SessionMap sessionMap;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "loginSession") String loginSession, @PathParam(value = "logNumber") String logNumber) throws Exception {
        this.session = session;
        this.loginSession = loginSession;
        this.logNumber = logNumber;
        createTime = new Date();
        if(sessionMap==null){
            sessionMap =ContextUtils.getBean(SessionMap.class);
        }
        if(webSocektList==null){
            webSocektList = ContextUtils.getBean(WebSocketList.class);
        }
        //验证loginSession是否有效
        if (sessionMap.get(loginSession) == null) {
            log.error("无效的登陆session:" + loginSession);
            throw new Exception("无效的登陆session!");
        }
        //加入websocket列表
        webSocektList.put(logNumber, this);
        log.debug("【websocket消息】有新的连接，");
    }


    @OnClose
    public void onClose() {
        webSocektList.remove(logNumber);
        log.debug("【websocket消息】连接断开");
    }


    @OnMessage
    public void onMessage(String message) {
        log.debug("【websocket消息】收到客户端消息:" + message);

    }


    /**
     * 此为单点消息
     */
    public void sendOneMessage(String message) {
        log.debug("【websocket消息】单点消息:" + message);
        try {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
                //session.getAsyncRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("发送单点消息失败!", e);
//          e.printStackTrace();

        }


    }


}